const path = require('path');
const { Worker } = require('worker_threads');
const URL = require('../utils/url');
const Default_Xml = require("../utils/xml");
const { getTokenLoginCookie } = require('./login');
const { DEFAULT_XML } = require("../constant/index")
const os = require('os');

async function publishBundle() {
    const [
        codeBranch = "OpenHarmony-3.0-LTS",
        version = "3.0.0-snapshot",
        loginUser = "8EBENJ2"
    ] = process.argv.slice(2)
    await getTokenLoginCookie(URL.login, { ignoreCache: true, loginUser });
    const default_xml = await Default_Xml.fromPath(DEFAULT_XML)
    const repoNames = default_xml.xmlData.slice(0, 2).map(item => item.name)
    const errlogs = []
    repoNames.forEach(repoName => {
        const worker = new Worker(path.resolve(__dirname, "..", "thread", "index.js"), {
            workerData: {
                repoName,
                version,
                destPath: default_xml.matchRepo(repoName),
                action: "publish",
                codeBranch
            }
        })
        worker.on("exit", exitCode => {
            if (exitCode===0){

            }
            if (workerCount === repoNames.length) {
                console.log(errlogs.join(os.EOL));
            }
        })
        worker.on("message", log => {
            errlogs.push(log)
        })
    })
}

publishBundle()